package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    @Resource
    private WeChatProperties weChatProperties;
    @Resource
    private UserMapper userMapper;
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        //发送请求到微信登录接口 获取openid GET https://api.weixin.qq.com/sns/jscode2session
        String openid = getOpenid(userLoginDTO.getCode());
        //openid是否为空, 为空则登录失败 抛出业务异常
        if (openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //根据openid查询用户信息 若不存在,则注册进表中
        User user = new User();
        user.setOpenid(openid);
        //构造查询条件 lambdaWrapper 通过openid查询
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getOpenid, openid);
        user = userMapper.selectOne(wrapper);
        if (user == null){
            user = new User();
            user.setOpenid(openid);
            userMapper.insert(user);
        }
        return userMapper.selectOne( wrapper);
    }
    private String getOpenid (String code){
        Map<String,String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        //返回的是json字符串
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        //将json字符串转换成对象
        JSONObject jsonObject = JSONObject.parseObject(json);
        return jsonObject.getString("openid");
    }
}
